package com.ge.advanced;

import com.ge.advanced.pojo.User;

import java.sql.*;

public class ReturnPK {

    public static void main(String[] args) throws Exception {

        // 数据库连接
        String url = "jdbc:mysql://localhost:3306/jdbc";
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);

        // 新增SQL
        String sql = "INSERT INTO USER (name, passwd) VALUES (?, ?)";
        // 传入Statement.RETURN_GENERATED_KEYS，告知JDBC在执行完SQL后需要返回自增主键值
        PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        // 创建对象并传入属性值
        User jackson = new User(null, "Jackson", "123456");
        statement.setString(1, jackson.getName());
        statement.setString(2, jackson.getPasswd());

        int result = statement.executeUpdate();
        if (result > 0) {
            System.out.println("执行成功");
            // 返回生成的主键值，类型为单行单列的ResultSet
            ResultSet resultSet = statement.getGeneratedKeys();
            if (resultSet.next()) {
                int key = resultSet.getInt(1);
                jackson.setId(key);
            }
            resultSet.close();
            System.out.println(jackson);
        } else {
            System.out.println("执行失败");
        }

        statement.close();
        connection.close();
    }
}
